package com.asiainfo.ai.admin.utils;

import cn.hutool.core.util.CharUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class NameConvert2code {
    /**
     * 如果传入参数中有汉字把汉字变为拼音，截取拼音首字母，多个汉字首字母拼接字符串，如果包含英文或者其他字符则不变输出
     *
     * @param param param
     * @return String
     */
    public static String charactersChanged2PinyinAndTakeFirstLetter(String param) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] input = param.trim().toCharArray();
        StringBuilder output = new StringBuilder();
        try {
            for (char c : input) {
                //忽略空格
                if (CharUtil.equals(c, ' ', true)) {
                    continue;
                }
                //判断字符是否是中文
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    output.append(temp[0].charAt(0));
                } else {
                    output.append(c);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            throw new RuntimeException("param=" + param + "中文名称转换出现异常", e);
        }
        return output.toString();
    }

}
